package nancal.mp.service

import cn.hutool.core.comparator.VersionComparator
import nancal.mp.db.mongo.extend.getAppDeploySetting
import nancal.mp.db.mongo.mor
import nbcp.base.comm.ApiResult
import nbcp.base.extend.AsString
import nbcp.base.extend.Important
import nbcp.base.utils.Base64Util
import nbcp.http.api.NexusClient
import nbcp.http.model.NexusAssetEntity
import nbcp.http.model.NexusComponentSearchResult
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Lazy
import org.springframework.stereotype.Service

@Service
class NexusService {
    companion object {
        private val logger = LoggerFactory.getLogger(this::class.java.declaringClass)
    }

    @Autowired
    @Lazy
    lateinit var nexusClient: NexusClient;


    fun getMetadata(
        envCode: String,
        continuationToken: String? = null
    ): ApiResult<NexusComponentSearchResult> {
        var appSetting = mor.dev.appDeploySetting.getAppDeploySetting(envCode);
        var nexusAuth = Base64Util.encode2Base64(
            appSetting.nexusServer.userName + ":" +
                    appSetting.nexusServer.password
        );

        var result = nexusClient.getComponents(
            nexusAuth,
            "maven-public",
            continuationToken
        )

        result.items = result.items?.filter {
            if (it.version.contains("$") ||
                it.version.contains("%")
            ) {
                logger.Important("${it.group}.${it.name} 版本${it.version}非法，跳过！")
                return@filter false;
            }
            return@filter true;
        }

        return ApiResult.of(result);
    }


    /**
     * 获取最新的版本
     *
     * @eg: http://nexus.cloudnk.cn/service/rest/v1/search/assets?repository=maven-snapshots&maven.groupId=cn.dev8&maven.artifactId=ktbase&maven.baseVersion=1.1.6-SNAPSHOT&maven.extension=jar&maven.classifier=&sort=version&direction=desc
     */
    fun getLastedJarVersion(
        envCode: String,
        groupId: String,
        artifactId: String,
        version: String? = null
    ): ApiResult<NexusAssetEntity> {
        var appSetting = mor.dev.appDeploySetting.getAppDeploySetting(envCode);
        var nexusAuth = Base64Util.encode2Base64(
            appSetting.nexusServer.userName + ":" +
                    appSetting.nexusServer.password
        );

        var result = nexusClient.searchAssets(
            "Bearer " + nexusAuth,
            "maven-public",
            null,
            groupId,
            artifactId,
            version,
            "pom",
            null
        )

        if (result.items.isNullOrEmpty()) {
            return ApiResult.of(NexusAssetEntity())
        }

        var maxVersion = result.items?.map { it.version }?.maxWith(VersionComparator()).AsString();

        return ApiResult.of(result.items?.firstOrNull { it.version == maxVersion })
    }


    fun getLastedNpmVersion(
        envCode: String,
        packageName: String
    ): ApiResult<NexusAssetEntity> {
        var appSetting = mor.dev.appDeploySetting.getAppDeploySetting(envCode);
        var nexusAuth = Base64Util.encode2Base64(
            appSetting.nexusServer.userName + ":" +
                    appSetting.nexusServer.password
        );

        var result = nexusClient.searchAssets(
            "Bearer " + nexusAuth,
            "npm-group",
            packageName,
            null,
            null,
            null,
            null,
            null
        )

        return ApiResult.of(result.items?.firstOrNull())
    }
}